package com.jxdinfo.hussar.example.common.schedulingtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.example.common.schedulingtask.dao.MdWorkshopMapper;
import com.jxdinfo.hussar.example.common.schedulingtask.dao.ProWorkorderMapper;
import com.jxdinfo.hussar.example.common.schedulingtask.model.MdWorkshop;
import com.jxdinfo.hussar.example.common.schedulingtask.model.ProWorkorder;
import com.jxdinfo.hussar.example.common.schedulingtask.service.MdWorkshopService;
import com.jxdinfo.hussar.example.common.schedulingtask.service.ProWorkorderService;
import com.jxdinfo.hussar.example.common.schedulingtask.vo.MdWorkshopVO;
import com.jxdinfo.hussar.example.common.schedulingtask.vo.ProWorkorderVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 生产工单表的定时任务
 */
@Component
@AllArgsConstructor
public class ProWorkerScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(ProWorkerScheduleTask.class);

    private ProWorkorderMapper proWorkorderMapper;
    private ProWorkorderService proWorkorderService;


    /**
     * @Author QiaoBin
     * @Date 2024/3/20 16:07
     * @Description 车间管理表的定时任务
     */
    @Scheduled(cron = "0 30 0 * * ?") // 每天的凌晨30执行一次
//    @Scheduled(cron = "*/5 * * * * ?")
    public void proWorkerTask(){
        extracted();
    }

    public void extracted() {
        logger.info("\n生产工单表-定时任务-开始执行");
        LocalDateTime nowTime = LocalDateTime.now();
        synchronized ("proWorkerTask"){
            logger.info("\n鲁银-开始查询pro_workorder表中最大的同步时间");
            LocalDateTime scheduleDate = proWorkorderMapper.selectMaxScheduleDate();
            logger.info("\n鲁银-结束查询pro_workorder表中最大的同步时间，查询结果scheduleDate={}",scheduleDate);
            String scheduleDateString = "";
            if (scheduleDate != null) {
                scheduleDateString = scheduleDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            //查询创建时间大于定时任务时间，查询出来后把所有数据全部插进去
            logger.info("\n用友-生产工单表-开始查询erp表中创建时间大于任务时间的数据,查询参数任务执行时间scheduleDateString={}", scheduleDateString);
            List<ProWorkorderVO> proWorkerOrderMoreList = proWorkorderMapper.selectMoreSchedule(scheduleDateString);
            logger.info("\n用友-生产工单表-结束查询erp表中创建时间大于任务时间的数据,查询结果proWorkerOrderMoreList={}，size={}", proWorkerOrderMoreList,proWorkerOrderMoreList.size());
            if (proWorkerOrderMoreList.size() > 0) {
                ArrayList<ProWorkorder> proWorkorderList = new ArrayList<>();
                for (int i = 0; i < proWorkerOrderMoreList.size(); i++) {
                    logger.info("\n用友-生产工单表-当前循环次数i={}", i);
                    ProWorkorderVO proWorkorderVO = proWorkerOrderMoreList.get(i);
                    ProWorkorder proWorkorder = new ProWorkorder();
                    proWorkorder.setWorkorderId(proWorkorderVO.getWorkorderId());  // 主键
                    proWorkorder.setWorkorderCode(proWorkorderVO.getWorkorderCode());  // 工单编码
                    proWorkorder.setWorkshopId(proWorkorderVO.getWorkshopId());  // 车间ID
                    proWorkorder.setWorkshopCode(proWorkorderVO.getWorkshopCode());  // 车间编码
                    proWorkorder.setWorkshopName(proWorkorderVO.getWorkshopName());  // 车间名称
                    proWorkorder.setOrderSource(proWorkorderVO.getOrderSource());  // 来源类型
                    proWorkorder.setSourceCode(proWorkorderVO.getSourceCode());  // 来源单据
                    proWorkorder.setProductId(proWorkorderVO.getProductId());  // 产品id
                    proWorkorder.setQuantity(proWorkorderVO.getQuantity());  // 生产数量
                    proWorkorder.setStatus(proWorkorderVO.getStatus());  // 单据状态
                    proWorkorder.setStartDate(proWorkorderVO.getStartDate());  // 计划开始日期
                    proWorkorder.setRequestDate(proWorkorderVO.getRequestDate());  // 计划完成日期
                    proWorkorder.setWarehouseId(proWorkorderVO.getWarehouseId());  // 仓库主键
                    proWorkorder.setProductCode(proWorkorderVO.getProductCode());  // 产品编码
                    proWorkorder.setProductName(proWorkorderVO.getProductName());  // 产品名称
                    proWorkorder.setProductSpc(proWorkorderVO.getProductSpc());  // 规格型号
                    proWorkorder.setMeasureId(proWorkorderVO.getMeasureId());  // 单位id
                    proWorkorder.setUnitOfMeasure(proWorkorderVO.getUnitOfMeasure());  // 单位名称
                    proWorkorder.setWarehouseCode(proWorkorderVO.getWarehouseCode());  // 仓库编码
                    proWorkorder.setWarehouseName(proWorkorderVO.getWarehouseName());  // 仓库名称
                    proWorkorder.setEnableFlag(proWorkorderVO.getEnableFlag());  // 生效状态
                    proWorkorder.setCreateBy(proWorkorderVO.getCreateBy());
                    proWorkorder.setCreateTime(proWorkorderVO.getCreateTime());
                    proWorkorder.setUpdateBy(proWorkorderVO.getUpdateBy());
                    proWorkorder.setUpdateTime(proWorkorderVO.getUpdateTime());
                    proWorkorder.setErpProId(proWorkorderVO.getWorkorderId());
                    proWorkorder.setScheduleTime(nowTime);
                    proWorkorder.setWorkorderName(
                            new StringBuilder()
                                    .append(proWorkorderVO.getProductName())
                                    .append("【")
                                    .append(proWorkorderVO.getQuantity().toString())
                                    .append("】")
                                    .append(proWorkorderVO.getUnitOfMeasure()).toString());// 工单名称
                    logger.info("\n用友-生产工单表-开始向list中存入数据，数据proWorkorder={},i={}", proWorkorder,i);
                    if (proWorkorder.getProductId() != null){
                        proWorkorderList.add(proWorkorder);
                    }
                }
                logger.info("\n用友-生产工单表-开始向pro_workorder表中插入数据，数据proWorkorderList={}", proWorkorderList);
                boolean b = proWorkorderService.saveBatch(proWorkorderList, 100);
                logger.info("\n用友-生产工单表-结束向pro_workorder表中插入数据，插入结果b={}", b);
            }
            if (scheduleDate == null) {
                logger.info("\n用友-生产工单表-查询不到任务时间，说明一次也没有同步，之间原封不动的插入就行,也就不需要更新");
                return;
            }
            if (scheduleDate != null) {
                //查询更新时间大于定时任务时间，查询出来后把所有数据全部更新进去
                logger.info("\n用友-生产工单表-开始查询erp更新时间大于任务时间，参数scheduleDateString={}", scheduleDateString);
                List<ProWorkorderVO> updateMoreSchedule = proWorkorderMapper.selectUpdateMoreSchedule(scheduleDateString);
                logger.info("\n用友-生产工单表-结束查询erp更新时间大于任务时间,查询结果updateMoreSchedule={},数量size={}", updateMoreSchedule, updateMoreSchedule.size());

                if (updateMoreSchedule == null || updateMoreSchedule.size() == 0) {
                    logger.info("\n用友-生产工单表-没有查询到更新时间大于任务时间的mes数据");
                    return;
                }
                // 转成map集合
                Map<Long, ProWorkorderVO> proOrkOrderUpdateMap = updateMoreSchedule.stream().collect(Collectors.toMap(ProWorkorderVO::getWorkorderId, t -> t));
                List<Long> masterIdList = updateMoreSchedule.stream().map(ProWorkorderVO::getWorkorderId).collect(Collectors.toList());
                logger.info("\n用友-生产工单表-更新时间大于任务时间的主键集合masterIdList={},size={}", masterIdList, masterIdList.size());

                logger.info("\n用友-生产工单表-开始查询pro_workorder中erp_id=erp表主键的数据,参数masterIdList={}", masterIdList);
                QueryWrapper<ProWorkorder> proWorkorderQueryWrapper = new QueryWrapper<>();
                proWorkorderQueryWrapper.in("workorder_id",masterIdList);
                proWorkorderQueryWrapper.eq("deleted_flag",0);
                List<ProWorkorder> moreUpdateList = proWorkorderMapper.selectList(proWorkorderQueryWrapper);
                logger.info("\n用友-生产工单表-结束查询pro_workorder中erp_id=erp表中主键的数据,结果moreUpdateList={},size={}", moreUpdateList, moreUpdateList.size());
                if (moreUpdateList.size() > 0) {
                    ArrayList<ProWorkorder> updateProWorkshopList = new ArrayList<>();
                    for (int i = 0; i < moreUpdateList.size(); i++) {
                        logger.info("\n用友-生产工单表-当前更新时间大于任务时间，mes_base_item表更新，次数i={}", i);
                        ProWorkorder proWorkorder = moreUpdateList.get(i);
                        Long currentMasterId = proWorkorder.getErpProId();
                        ProWorkorderVO proWorkorderVO = proOrkOrderUpdateMap.get(currentMasterId);
                        proWorkorder.setWorkorderCode(proWorkorderVO.getWorkorderCode());  // 工单编码
                        proWorkorder.setOrderSource(proWorkorderVO.getOrderSource());  // 来源类型
                        proWorkorder.setWorkshopId(proWorkorderVO.getWorkshopId());  // 车间ID
                        proWorkorder.setWorkshopCode(proWorkorderVO.getWorkshopCode());  // 车间编码
                        proWorkorder.setWorkshopName(proWorkorderVO.getWorkshopName());  // 车间名称
                        proWorkorder.setSourceCode(proWorkorderVO.getSourceCode());  // 来源单据
                        proWorkorder.setProductId(proWorkorderVO.getProductId());  // 产品id
                        proWorkorder.setQuantity(proWorkorderVO.getQuantity());  // 生产数量
                        proWorkorder.setStatus(proWorkorderVO.getStatus());  // 单据状态
                        proWorkorder.setStartDate(proWorkorderVO.getStartDate());  // 计划开始日期
                        proWorkorder.setRequestDate(proWorkorderVO.getRequestDate());  // 计划完成日期
                        proWorkorder.setWarehouseId(proWorkorderVO.getWarehouseId());  // 仓库主键
                        proWorkorder.setProductCode(proWorkorderVO.getProductCode());  // 产品编码
                        proWorkorder.setProductName(proWorkorderVO.getProductName());  // 产品名称
                        proWorkorder.setProductSpc(proWorkorderVO.getProductSpc());  // 规格型号
                        proWorkorder.setMeasureId(proWorkorderVO.getMeasureId());  // 单位id
                        proWorkorder.setUnitOfMeasure(proWorkorderVO.getUnitOfMeasure());  // 单位名称
                        proWorkorder.setWarehouseCode(proWorkorderVO.getWarehouseCode());  // 仓库编码
                        proWorkorder.setWarehouseName(proWorkorderVO.getWarehouseName());  // 仓库名称
                        proWorkorder.setEnableFlag(proWorkorderVO.getEnableFlag());  // 生效状态
                        proWorkorder.setCreateBy(proWorkorderVO.getCreateBy());
                        proWorkorder.setCreateTime(proWorkorderVO.getCreateTime());
                        proWorkorder.setUpdateBy(proWorkorderVO.getUpdateBy());
                        proWorkorder.setUpdateTime(proWorkorderVO.getUpdateTime());
                        proWorkorder.setErpProId(proWorkorderVO.getWorkorderId());
                        proWorkorder.setScheduleTime(nowTime);
                        proWorkorder.setWorkorderName(
                                new StringBuilder()
                                        .append(proWorkorderVO.getProductName())
                                        .append("【")
                                        .append(proWorkorderVO.getQuantity().toString())
                                        .append("】")
                                        .append(proWorkorderVO.getUnitOfMeasure()).toString());// 工单名称
                        logger.info("\n用友-生产工单表-向updateProWorkshopList中存储待要更新的生产工单表信息,proWorkorder={}", proWorkorder);
                        if (proWorkorder.getProductId() != null){
                            updateProWorkshopList.add(proWorkorder);
                        }
                    }
                    logger.info("\n用友-生产工单表-开始更新pro_workorder数据,列表updateProWorkshopList={}", updateProWorkshopList);
                    boolean u = proWorkorderService.updateBatchById(updateProWorkshopList);
                    logger.info("\n用友-生产工单表-结束更新pro_workorder数据,更新结果u={}", u);
                }
            }
        }
        logger.info("\n生产工单表-定时任务-结束执行");
    }
}
